<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-05-03
 * Time: 11:00
 */

namespace app\admin\model;


use app\common\exception\HaveUseException;
use app\common\exception\ParameterException;
use app\common\model\BaseModel;
use app\common\validate\IDCollection;
use think\facade\Db;
use think\model\concern\SoftDelete;
use app\admin\validate\AuthMenu as Validate;
use service\TreeService;

class AuthMenu extends BaseModel
{
    protected $hidden = ['update_time','delete_time'];

    use SoftDelete;
    protected $deleteTime = 'delete_time';

    public function getLabelAttr($value, $data)
    {
        return $data['name'] . '(' . $data['title'] . ')';
    }

    /**
     * 获取Table的tree数据
     * @param array $params
     * @return array
     */
    public static function getTableTreeData(array $params)
    {
        $static = new static();

        $static = $static->order('sort','asc');

        foreach ($params as $name => $value) {
            $value = trim($value);
            switch ($name) {
                case 'name':
                    if (!empty($value)) {
                        $like_text = '%' . $value . '%';
                        $static = $static->whereLike('name', $like_text);
                    }
                    break;
                case 'title':
                    if (!empty($value)) {
                        $like_text = '%' . $value . '%';
                        $static = $static->whereLike('title', $like_text);
                    }
                    break;
                case 'pid':
                    if (!empty($value)) {
                        $static = $static->where('pid','=',intval($value));
                    }
                    break;
            }
        }

        $data = $static->select();

        $data = $data ? $data->toArray() : [];

        return TreeService::elementTableTree($data);
    }

    /**
     * 获取ElementTree树形结构数据
     * @return array
     */
    public static function getElementTreeData()
    {
        $data = static::where([['status','=',1]])
            ->field('id,pid,title')
            ->order('sort','asc')
            ->select();
        $data = $data ? $data->toArray() : [];

        $select = static::where([['public_menu','=',1]])
            ->column('id');

        return TreeService::elementTree($data, $select);
    }

    /**
     * 获取角色权限菜单的全部节点信息
     * @return array
     */
    public static function getAllMenuNode()
    {
        $data = static::getDataWithField([['status','=',1]],['id','pid','name','title'],['sort'=>'asc']);

        $data =  $data->isEmpty() ? [] : $data->append(['label'])->toArray();

        return TreeService::elementOptionsGroup($data);
    }

    /**
     * 获取角色权限菜单的全部父节点信息
     * @return array
     */
    public static function getAllParentNode()
    {
        $data = static::where([['pid','=',0],['status','=',1]])
            ->field('id,name,title')
            ->order('sort','desc')
            ->select();

        if ($data) {
            return $data->toArray();
        } else {
            return [];
        }
    }

    /**
     * 添加权限菜单
     * @param array $data
     * @return bool
     */
    public static function addAuthMenu(array $data)
    {
        $validate = new Validate();
        if (!$validate->scene('add')->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError()
            ]);
        }

        $static = static::create($data);
        if (isset($static->id) && $static->id > 0) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 编辑权限菜单
     * @param array $data
     * @return bool
     */
    public static function editAuthMenu(array $data)
    {
        $validate = new Validate();
        if (!$validate->scene('edit')->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError()
            ]);
        }

        $static = static::find($data['id']);
        static::checkTopHaveChild($data['id'],$static->pid,$data['pid']);

        $result = $static->allowField(['id','pid','name','title','path','url',
            'redirect','icon','is_link','hidden','is_click_in_breadcrumb',
            'always_show','no_cache','breadcrumb_show','public_menu','sort','status'])
            ->save($data);
        if ($result !== false) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 删除角色权限菜单数据
     * @param $ids
     * @return bool
     */
    public static function delAuthMenu($ids)
    {
        $validate = new IDCollection();
        if (!$validate->check([
            'ids' => $ids
        ])) {
            throw new ParameterException([
                'msg' => $validate->getError()
            ]);
        }

        // 获取全部菜单的id和pid数据
        $allAuthMenuData = static::getDataWithField([],['id','pid'])
            ->toArray();
        $allID = [];    //保存所有的相关id，如果是顶级节点会获取其下面的子元素
        //判断是否为数组，然后将字符串转为数组
        if (!is_array($ids)){
            $ids = explode(',',$ids);
        }
        foreach ($ids as &$id) {
            //将id数组的字符转换成整数
            $id = intval($id);
            //判断是否有重复的数据
            if (in_array($id,$allID)){
                continue;
            }

            //获取对应id下的子id
            $allID = array_merge($allID,TreeService::getChildrenPid($allAuthMenuData,$id,'id','pid',true));
        }
        //把主id也添加进去
        $allID = array_merge($allID,$ids);
        //去除重复值
        $allID = array_unique($allID);

        // 判断是否还有角色使用
        $role_data = Db::name('auth_role')->alias('a')
            ->join('auth_role_menu r', 'r.role_id = a.id')
            ->whereIn('r.menu_id',$allID)
            ->column('a.id');
        if (!empty($role_data)) {
            throw new HaveUseException([
                'msg' => '还有权限角色使用该菜单'
            ]);
        }

        if (static::destroy($allID) !== false) {
            return true;
        } else {
            return false;
        }
    }
}